﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Convertor.Plugin.WebDownloader
{
    class HttpUtils
    {
        HttpWebRequest request = null;

        public HttpWebRequest Request
        {
            get { return request; }
        }
        HttpWebResponse response = null;

        public HttpWebResponse Response
        {
            get { return response; }
        }
        StreamWriter sw = null;

        public StreamWriter Sw
        {
            get { return sw; }
        }
        Stream responseStream = null;

        public Stream ResponseStream
        {
            get { return responseStream; }
        }
        Stream requestStream = null;

        public Stream RequestStream
        {
            get { return requestStream; }
        }

        private ConfigContent config;

        public HttpUtils(ConfigContent config, Uri url)
        {
            this.config = config;
            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ServicePoint.Expect100Continue = false;
            request.Accept = config.Accept;
            request.UserAgent = config.UserAgent;
            request.Referer = config.UrlReferrer;
            request.ContentType = config.ContentType;
            WebHeaderCollection c = new WebHeaderCollection();
            c.Add(HttpRequestHeader.AcceptCharset, config.AcceptCharset);
            c.Add(HttpRequestHeader.AcceptLanguage, config.AcceptLanguage);
            if (!string.IsNullOrEmpty(config.Cookie))
            {
                c.Add(HttpRequestHeader.Cookie, config.Cookie);
            }
            request.Headers.Add(c);
        }
    
        /// <summary>
        /// HTTP POST方式请求数据
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="param">POST的数据</param>
        /// <returns></returns>
        public void Post(string param)
        {
            string responseStr = string.Empty;

            try
            {
                request.Method = "POST";

                requestStream = request.GetRequestStream();
                sw = new StreamWriter(requestStream);
                sw.Write(param);
                sw.Close();

                response = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// HTTP GET方式请求数据.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <returns></returns>
        public void Get()
        {
            request.Method = "GET";

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void Post(IDictionary<object, object> param, string picPath)
        {
            FileStream fileStream = new FileStream(picPath, FileMode.Open, FileAccess.Read);
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream rs = request.GetRequestStream();
            string responseStr = string.Empty;

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in param.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, param[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, "pic", new FileInfo(picPath).Name, "text/plain");//image/jpeg
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();
            //rs.Close();

            //rs.Write(fileByte, 0, fileByte.Length);

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                if (response != null)
                {
                    response.Close();
                }
            }
        }

    }
}
